package com.example.demo.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author xiangyu
 * @Date 2021/12/24 14:37
 * @Version 1.0
 */

class Cache{

    ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    public void putCache(){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+" "+"putCache begin");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+" "+"putCache end");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void getCache(){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+" "+"getCache begin");
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName()+" "+"getCache end");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }
    }

}

public class ReadWriteLockDemo {

    public static void main(String[] args) {
        Cache cache=new Cache();
        for (int i=0;i<5;i++){
            new Thread(()->{
                cache.getCache();
            }).start();
        }

        for (int i=0;i<5;i++){
            new Thread(()->{
                cache.putCache();
            }).start();
        }
    }
}
